package fr.fleroy.gedappservices.dao;

import fr.fleroy.geddatamodel.bean.FileBean;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

/**
 *
 * @author fLeroy
 */
@Repository("fileDao")
@Scope("singleton")
public class FileDao extends AbstractDao implements IFileDao{

    /**
    * Logger
    */
    private final static Logger LOGGER = Logger.getLogger(FileDao.class);

    @Override
    public int uploadFile(FileBean poFile) throws Exception{
        LOGGER.debug("dans uploadFile(FileBean poFile) : " + poFile);
        Object[] laParams = new Object[]{
				poFile.getName(),
                                poFile.getAbsolutePath()
	};
        return getTemplate().update("insert into fichier(Nom,URL) values(?,?)", laParams);
    }

    @Override
    public void insertKeys(int pnId,String pskey) throws Exception{
         LOGGER.debug("dans insertKeys(int lnId) : " + pnId);
         Object[] laParams = new Object[]{ pnId,pskey };
         getTemplate().update("insert into metadonnee(IdFile,Libelle) values(?,?)", laParams);
    }

    @Override
    public int getLastId() throws Exception{
         return getTemplate().queryForInt("select LAST_INSERT_ID()");
    }

    @Override
    public List<FileBean> searchFileForKey(final String psKey) {
        LOGGER.debug("dans searchFileForKey(List<String> poKeys) : " + psKey);
        Object[] laParams = new Object[]{ psKey };
        List<FileBean> loRes = getTemplate().query("select IdFile,URL from fichier f, metadonnee m where f.IdFile=m.IdFile and m.Libelle like '%?%'",laParams, new RowMapper() {
                @Override
                public Object mapRow(final ResultSet poRs,final int pnIdx) throws SQLException {
                        FileBean loFile = new FileBean(poRs.getString("URL"));
                        loFile.setId(poRs.getInt("IdFile"));
                        loFile.getAttributs().add(psKey);
                        return loFile;
                }
        });
        return loRes;
    }

}
